<template>
  <div>
    <!-- 页面表格数据渲染 -->
    <en-table-layout toolbar pagination :loading="loading" @sort-change='tableSortChange' @selection-change="handleSelectionChange"
      :tableData="tableData" stripe :header-cell-style="{textAlign: 'center'}"
      :style="{width: '100%'}" :height="tableHeight">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <!-- 顶部六个按钮 -->
          <el-button size="mini" type="primary" @click="deliveryOrder()">批量发货</el-button>
          <el-button size="mini" @click="openDialog()" type="primary">打印小票</el-button>
          <!-- <el-button size="mini" type="primary">打印分拣单</el-button>
          <el-button size="mini" type="primary">打印配送单</el-button> -->
          <el-button size="mini" type="primary" @click="auditIt()">多退少补</el-button>
          <el-button size="mini" type="primary" @click="exportOrder" icon="el-icon-download">导出Excel</el-button>
          <el-button type="text"><a href="https://egale-shop.oss-cn-hangzhou.aliyuncs.com/XP58mm%20Driver.zip">打印驱动下载</a></el-button>
        </div>
        <div class="toolbar-search">
          <!-- 顶部搜索栏 -->
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" advanced advancedWidth="465" placeholder="请输入关键字">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm"  label-width="95px">
                <el-form-item label="订单号" class="toolbar-input" prop="op_status">
                  <el-input v-model="advancedForm.order_sn" clearable placeholder="订单号"></el-input>
                </el-form-item>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="站长姓名" class="toolbar-input" prop="leader_name">
                      <el-input v-model="advancedForm.leader_name" clearable placeholder="站长姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属团长" class="toolbar-input" prop="leader_team">
                      <el-input v-model="advancedForm.leader_team" clearable placeholder="所属团长"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="收货人姓名" class="toolbar-input" prop="ship_name">
                      <el-input v-model="advancedForm.ship_name" clearable placeholder="收货人姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="收货人电话" class="toolbar-input" prop="ship_mobile">
                      <el-input v-model="advancedForm.ship_mobile" clearable placeholder="收货人电话"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="订单状态" class="toolbar-input" prop="order_status">
                      <el-select v-model="advancedForm.order_status" placeholder="订单状态" class="select-get" clearable>
                        <el-option v-for="option in s_order_type" :label="option.name" :value="option.id" :key="option.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="配送方式" class="toolbar-input" prop="shipping_type">
                        <el-select v-model="advancedForm.shipping_type" placeholder="配送方式" class="select-get" clearable>
                          <el-option v-for="(option,index) in s_shipping_way" :label="option.label" :value="option.value" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="小票打印" prop="print_times" class="toolbar-input">
                      <el-select v-model="advancedForm.print_times" clearable>
                        <el-option label="已打印" value="1"></el-option>
                        <el-option label="未打印" value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="12">
                    <el-form-item label="排序类型" class="toolbar-input" prop="order_field">
                      <el-select v-model="advancedForm.order_field" clearable>
                        <el-option label="分拣单号" value="SORTING"></el-option>
                        <el-option label="自提站点" value="SITE"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="12">
                    <el-form-item label="会员名称" class="toolbar-input" prop="member_nick_name">
                      <el-input v-model="advancedForm.member_nick_name" placeholder="会员名称" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="下单时间" class="toolbar-input">
                  <el-date-picker
                    v-model="advancedForm.order_time_range"
                    type="datetimerange"
                    align="center"
                    :editable="false"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :default-time="['00:00:00', '23:59:59']">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
      <!-- 列表渲染 -->
      <template slot="table-columns">
        <el-table-column type="selection" width="50" fixed></el-table-column>
        <el-table-column prop="sn" min-width="140" label="订单号">
          <template slot-scope="{ row }">
            <span class="sn-color" @click="handleGroupDetail(row)">{{ row.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="leader_name" min-width="100" label="站长姓名" sortable="custom"/>
        <!-- <el-table-column min-width="100" label="分拣单号" sortable="custom" prop="sorting_seq">
          <template slot-scope="scope">
            <span style="color: #16d429;" >{{scope.row.sorting_batch}}_{{scope.row.sorting_seq}}</span>
          </template>
        </el-table-column> -->
        <el-table-column min-width="150" label="下单时间" prop="create_time" sortable="custom">
          <template slot-scope="scope">{{ scope.row.create_time | unixToDate("MM-dd hh:mm:ss") }}</template>
        </el-table-column>
        <el-table-column min-width="400" label="购买商品" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.sku_list" :key="index" class="mytable">
              <div>
                <img :src="item.goods_image" class="goods-image"/>
              </div>
              <div class="goods-name">
                <a :href="`${MixinBuyerDomain}/goods/${item.goods_id}`" target="_blank" style="color: #00a2d4;">
                  <span>{{item.name}}</span>
                  <span v-for="(list,index) in item.spec_list" :key="index">,{{list.spec_value}}</span>
                  <span style="color: #d42725;" >×{{item.num}}</span>
                  <span style="color: #00a2d4;">,单价￥{{item.purchase_price}}</span>
                  <span style="color: #00a2d4;">,小计￥{{item.actual_pay_total}}</span>
                </a>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="order_status_text" min-width="80" label="订单状态" />
        <el-table-column min-width="80" label="售后状态" >
          <template slot-scope="scope">
            <span :class="scope.row.service_status=='APPLY'?'bottomred':''">{{scope.row.service_status=='APPLY'?'已申请':scope.row.service_status=='NOT_APPLY'?'未申请':scope.row.service_status=='EXPIRED'?'已失效':''}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="print_times" min-width="80" label="打印次数" >-->
<!--          <template slot-scope="{ row }">-->
<!--            <span :class=" row.print_times === 0 ? 'font-color' : '' ">{{row.print_times}}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="member_nick_name" min-width="130" label="买家昵称" />
        <el-table-column prop="ship_name" min-width="130" label="收货人" />
        <el-table-column prop="ship_mobile" min-width="120" label="收货电话" />
        <el-table-column min-width="120" label="收货地址" >
          <template slot-scope="scope">
            <span>{{(scope.row.ship_city + scope.row.ship_county + scope.row.ship_town+ scope.row.ship_addr) || '无'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="site_name" min-width="80" label="站长姓名" />
        <el-table-column prop="leader_mobile" min-width="100" label="站长手机号" />
        <el-table-column prop="pick_address" min-width="120" label="站点地址" />
        <el-table-column prop="real_name" min-width="80" label="团长姓名" />
        <el-table-column prop="mobile" min-width="120" label="团长手机号" />
        <el-table-column prop="payment_method_name" min-width="100" label="付款渠道" />
        <el-table-column label="配送方式" >
          <template slot-scope="scope">
              <span>{{scope.row.shipping_type==='SELF'?"站点自提":"快递到家"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="shipping_price" min-width="80" label="运费" />
        <el-table-column prop="discount_price" min-width="100" label="优惠金额" />
        <el-table-column prop="order_price" min-width="100" label="订单金额" />
        <el-table-column prop="pay_money" min-width="100" label="实付金额" />
        <el-table-column prop="remark" min-width="100" label="订单备注" />
        <el-table-column min-width="140" label="发货时间">
          <template slot-scope="scope">{{ scope.row.ship_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</template>
        </el-table-column>
        <!-- <el-table-column prop="logi_name" min-width="100" label="物流公司" />
        <el-table-column prop="ship_no" min-width="140" label="运单号" /> -->
        <el-table-column prop="receive_time" min-width="100" label="收货时间" />
        <el-table-column min-width="100" label="订单类型" >
          <template slot-scope="scope">
              <span>{{ scope.row.order_type | filterDict('order_type')}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cancle_time" min-width="100" label="取消时间" />
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="uploadReceipt(scope.row)">修改地址</el-button>
          </template>
        </el-table-column>
      </template>
      <!-- 分页列表 -->
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog
      :title="'已选中'+multipleSelection.length+'个订单'"
      :visible.sync="DialogVisible"
      width="300px"
      :append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div id="mycontent" style="display:none;">
        <div id="advancePrint" style="padding:10px;box-sizing:border-box;">
          <div v-for="(item,index) in printOrder" :key="index" class="previewDiv">
            <div style="text-align: left;font-size:14px; white-space:nowrap;font-weight: bold;padding-top:20px">订单号：{{item.sn}}</div>
            <div style="text-align: left;white-space:nowrap;font-size:14px;font-weight: bold">下单时间：{{item.create_time | unixToDate("yyyy-MM-dd hh:mm") }}</div>
            <div style="text-align: left;margin-bottom:10px;font-size:14px;font-weight: bold">配送方式：{{item.shipping_type === 'SELF' ? "站点自提" : "快递到家"}}</div>
            <!-- <div style="margin-bottom:20px;">{{item.create_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</div> -->
            <div style="width:100%; border-top:dashed 1px black; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; line-height:5px; text-align: center;">
              <span style="font-weight:bold; font-size: 20px; background: #fff; padding-left:10px; padding-right:10px; z-index:999;">#{{item.order_seq === null ? '' : item.order_seq}}</span>
            </div>
            <div style="text-align: center;"><span>{{item.seller_name}}</span></div>
            <div style="text-align: center; font-weight: bold; font-size:20px; margin-top:10px;">{{item.cancel_reason}}</div>
            <!-- 二维码 -->
              <div style="text-align:center;">
                  <barcode :value="item.sn" :width="1.5" :font-size="15"  :height="40" :displayValue="false">
                    条形码显示失败
                  </barcode>
              </div>
            <div style="width:100%;display:flex;border-top:1px dashed black;border-bottom:1px dashed black;" >
              <div style="flex:2;padding:6px 0;font-weight:800;">商品名称</div>
              <div style="flex:1;padding:6px 0;font-weight:800;">数量</div>
              <div style="flex:1;padding:6px 0;font-weight:800;">单价</div>
            </div>
            <div v-for="(count,index) in item.order_sku_list" :key="index">
              <div style="display:flex;align-items:flex-start">
                <span style="flex:2;padding:6px;font-size:14px;">{{count.name}}</span>
                <span style="flex:1;font-weight:600;padding:6px;font-size:14px;">{{"×"+count.num}}</span>
                <span style="flex:1;padding:6px;font-size:14px;">{{count.purchase_price}}</span>
              </div>
            </div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:6px; text-align: center;"></div>
            <div style="margin-bottom:10px;">配送费：{{item.shipping_price}}</div>
            <div style="font-weight:bold; font-size: 20px;">合计：{{item.order_price}}</div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:20px; line-height:5px; text-align: center;"></div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">自提站点：{{item.leader.site_name}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">站长姓名：{{item.leader.leader_name}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">站长电话：{{item.leader.leader_mobile}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold;">站点地址：{{item.leader.city}} {{item.leader.county}} {{item.leader.address}}</div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:20px; line-height:5px; text-align: center;"></div>
            <div style="font-weight:bold; font-size: 16px;">
              <div>
              {{item.ship_province}}{{item.ship_city}}{{item.ship_county}}{{item.ship_addr}}
              </div>
              <div>
                {{item.ship_mobile}}
              </div>
              <div>
                {{item.ship_name}}
              </div>
            </div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:30px; margin-top:10px; line-height:5px; text-align: center;"></div>
            <div style="text-align: left;font-size:12px; white-space:nowrap;">订单号：{{item.sn}}</div>
            <div style="text-align: left;white-space:nowrap;font-size:12px;margin-top:6px">下单时间：{{item.create_time | unixToDate("yyyy-MM-dd hh:mm") }}</div>
            <div style="width:100%; border-top:dashed 1px black; height:5px;
              padding-bottom:70px; line-height:5px; text-align: center; margin-top:20px;">
              <span style="font-weight:bold; font-size: 20px; background: #fff; padding-left:10px; padding-right:10px;  z-index: 9999;"> #{{item.order_seq === null ? '' : item.order_seq}}完</span>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="infooter">
          <el-button type="primary" @click="printPdf()" :loading="btn_loading">{{printText}}</el-button>
          <el-button type="primary" @click="previewOrder()">预览</el-button>
          <el-button @click="DialogVisible=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="选择商品发货"
      :visible.sync="goodDialogVisible"
      width="600px"
      :append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="myred">已选中<span>{{multipleSelection.length}}</span>笔订单进行发货操作，请再次确认！</div>
      <el-form :model="goodSendForm" :rules="goodSendFormRules" ref="goodSendFormRef" label-width="100px">
      <el-form-item  label="发货方式：" prop="shipping_type">
        <el-radio-group v-model="goodSendForm.shipping_type">
          <el-radio label="GLOBAL">快递发货<span class="bottomred">（客户要求）</span></el-radio>
          <el-radio label="LOCAL">同城配送</el-radio>
          <el-radio label="SELF">客户自提</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="goodSendForm.shipping_type!=='SELF'" label="快递公司" prop="logi_id">
        <el-select v-model="goodSendForm.logi_id" class="select-type" clearable>
          <el-option
            v-for="option in s_logi_option"
            :label="option.name"
            :value="option.id"
            :key="option.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="goodSendForm.shipping_type!=='SELF'" label="快递单号" prop="ship_no">
        <el-input v-model="goodSendForm.ship_no" placeholder="请输入快递单号"></el-input>
      </el-form-item>
    </el-form>
      <div class="footer">
        <div class="infooter">
          <el-button type="primary" @click="sendGoods('')">确定</el-button>
          <el-button @click="goodDialogVisible=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="多退少补" width="40%" :visible.sync="auditDialog" class="modify-model">
      <el-form
        label-width="100px"
        size="small"
        :model="moreRefundForm"
        :rules="moreRefundRules"
        ref="moreRefundForm">
        <div class="top-dialog">已选中<span class="bottomred">{{selectLength}}</span>笔订单多退少补，请仔细确认！</div>
        <el-form-item label="退补类型:" prop="refund_type">
          <el-radio-group v-model="moreRefundForm.refund_type">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-radio :label="moreRefundForm.refund_type">多付退款</el-radio>
              </el-col>
              <el-col :span="12">
                <el-radio disabled label="少付补缴"></el-radio>
              </el-col>
            </el-row>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退补金额:" prop="test">
          <el-radio-group v-model="moreRefundForm.test" @change="handleRefundMoney">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-radio class="math-number" label="1">随机数</el-radio>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="max_refund">
                  <el-input type="number" v-model="moreRefundForm.max_refund" placeholder="最大值"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="min_refund">
                  <el-input type="number" v-model="moreRefundForm.min_refund" placeholder="最小值"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" class="distance">
                <el-col :span="5">
                  <el-radio class="math-number" label="2">固定数</el-radio>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="fix_refund">
                    <el-input v-model="moreRefundForm.fix_refund" placeholder="固定金额"></el-input>
                  </el-form-item>
                </el-col>
            </el-row>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退补原因:" prop="refund_reason">
          <el-row :gutter="20">
            <el-select v-model="moreRefundForm.refund_reason" placeholder="请选择">
              <el-option v-for="(item,index) in refundreasons" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-row>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="具体描述:" prop="refund_description">
              <el-input type="textarea" v-model="moreRefundForm.refund_description"  maxlength="100"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer mt5">
        <el-button size="small" type="primary"  @click="submitAudit('moreRefundForm')">确 定</el-button>
        <el-button size="small" @click="handlerCancel()">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改收货人信息 -->
    <el-dialog title="修改收货地址" width="500px" :visible.sync="receiptDialog">
      <el-form
        :model="receiptForm"
        ref="receiptForm"
        labelWidth="100px"
        :rules="receiptFormRules">
        <el-form-item v-show="false" prop="order_sn">
          <el-input type="hidden" v-model="receiptForm.order_sn"></el-input>
        </el-form-item>
        <el-form-item prop="shipping_type" label="配送方式:">
          <el-radio-group v-model="receiptForm.shipping_type">
            <el-radio label="SELF">站点自提</el-radio>
            <el-radio label="GLOBAL">配送到家</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="receiptForm.shipping_type==='SELF'">
          <el-form-item label="收货区域:" prop="site_name">
            <el-select
              v-model="receiptForm.leader_id"
              filterable
              remote
              clearable
              placeholder="请选择自提站点"
              :remote-method="remoteMethod">
              <el-option
                v-for="(item,index) in siteNames"
                :key="index"
                :label="`${item.leader_name}-${item.site_name}-${item.address}`"
                :value="item.leader_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收货人员:" style="margin-bottom: 0;">
            <el-col style="width:175px;margin-right:10px;">
              <el-form-item prop="ship_name">
                <el-input v-model="receiptForm.ship_name" placeholder="请输入收货人姓名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col style="width:175px;">
              <el-form-item prop="ship_mobile">
                <el-input v-model="receiptForm.ship_mobile" placeholder="请输入收货人姓名" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="收货人员:" style="margin-bottom: 0;">
            <el-col style="width:175px;margin-right:10px;">
              <el-form-item prop="ship_name">
                <el-input v-model="receiptForm.ship_name" placeholder="请输入收货人姓名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col style="width:175px;">
              <el-form-item prop="ship_mobile">
                <el-input v-model="receiptForm.ship_mobile" placeholder="请输入收货人姓名" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item prop="index_region" label="收货区域:">
            <en-region-picker :api="MixinRegionApi" :default="areas" @changed="(object) => { receiptForm.index_region = object.last_id }" clearable></en-region-picker>
          </el-form-item>
          <el-form-item prop="ship_addr" label="详细地址:">
            <el-input v-model="receiptForm.ship_addr" placeholder="详细地址" clearable></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="receiptDialog = false">取 消</el-button>
        <el-button type="primary" @click="receiptSubmit('receiptForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_LEADER from '@/api/leader';
import * as API_ORDER from '@/api/order';
import * as API_Receipt from '@/api/receipt';
import { getLodop } from '../../utils/LodopFuncs';
import { getDictData, filterShowDict } from '@/common/filter-show';
import VueBarcode from 'vue-barcode';
export default {
  name: 'leaderOrder',
  components: {
    'barcode': VueBarcode
  },
  data() {
    return {
      // 基本公用数据
      loading: false,
      remote_loading: false,
      valueSN: 'test',
      btn_loading: false,
      site: ['快递站', '便利店', '小卖部', '小超市', '洗衣店', '其他'],
      // 关联用户用到的数据
      options: [],
      // 自提站点的数据
      siteNames: [],
      list: [],
      // 配送方式
      s_shipping_way: [
        { label: '自提', value: 'SELF' },
        // { label: '同城配送', value: 'LOCAL' },
        { label: '物流', value: 'GLOBAL' }
      ],
      //站点类型下拉框
      s_order_type: [
        { id: 'ALL', name: '全部' },
        { id: 'WAIT_PAY', name: '待付款' },
        { id: 'WAIT_SHIP', name: '待发货' },
        { id: 'WAIT_ROG', name: '待收货' },
        { id: "ROG", name: "已收货" },
        { id: 'WAIT_COMMENT', name: '待评价' },
        { id: 'COMPLETE', name: '已完成' },
        { id: 'CANCELLED', name: '已取消' }
      ],
      // 退补原因下拉框
      refundreasons: [
        {
          label: '重量误差',
          value: 'WEIGHT_ERROR'
        },
        {
          label: '活动优惠',
          value: 'PREFERENTIAL_ACTIVITIES'
        },
        {
          label: '价格错误',
          value: 'PRICE_ERROR'
        }
      ],
      // 对话框数据
      DialogVisible: false,
      goodDialogVisible: false,
      receiptDialog: false,
      // 修改收货地址表单
      receiptForm: {
        order_sn: undefined,
        shipping_type: undefined,
        ship_name: undefined,
        ship_mobile: undefined,
        site_name: undefined,
        ship_addr: undefined
      },
      /** 地区信息*/
      areas: [],
      //查询表单内的数据
      advancedForm: {
        //关键字
        member_id: '',
        // 营业状态
        order_sn: '',
        // 所属团长
        leader_team: '',
        // 站长姓名
        leader_name: '',
        ship_mobile: '',
        shipping_type: '',
        order_status: '',
        order_field: '',
        order_time_range: [new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date()],
        member_nick_name: ''
      },
      // 分页参数配置
      params: {
        page_no: 1,
        page_size: 50,
        order_fields: []
      },
      // 添加表单验证
      goodSendFormRules: {
        shipping_type: [
          { required: true, message: '请选择发货方式', trigger: 'blur' }
        ]
      },
      // 物流公司名称下拉框 类似于option
      s_logi_option: [],
      // 批量发货数据表单
      goodSendForm: {
        shipping_type: '',
        logi_id: '',
        ship_no: ''
      },
      /** 列表数据 */
      tableData: [],
      /** 列表分页数据 */
      pageData: [],
      multipleSelection: [],
      /** 订单打印需要的数据 */
      printOrder: [],
      printText: '打印小票',
      auditDialog: false,
      // 选中的数据
      selectLength: 0,
      // 多退少补
      moreRefundForm: {
        refund_type: 'SPREAD_REFUND',
        test: undefined,
        refund_reason: undefined,
        refund_description: undefined,
        max_refund: undefined,
        min_refund: undefined,
        fix_refund: undefined
      },
      // 修改收货人信息表单验证
      receiptFormRules: {
        leader_id: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        ship_name: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        index_region: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        ship_mobile: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        ship_addr: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 多退少补表单验证
      moreRefundRules: {
        // refund_type: [
        //   { required: true, message: '请选择退补类型', trigger: 'blur' }
        // ],
        test: [
          { required: true, message: '退补金额最少选择一个!', trigger: 'blur' }
        ],
        refund_reason: [
          { required: true, message: '请选择退补原因', trigger: 'blur' }
        ]
      },
      event: undefined,
      sorting: '',
      ctm: '',
      sites: ''
    };
  },
  /**
    * @date 2020/08/20
    * @author kjh
    * @description {表格高度自适应屏幕尺寸}
  */
  computed: {
    tableHeight: function (){
      return document.documentElement.clientHeight - 225 + 'px';
    }
  },
  filters: {
    // 字典显示转换
    filterDict (_stateVal, _dictType) {
      return filterShowDict(_dictType, _stateVal);
    }
  },
  mounted() {
    // 获取格式化字典数据
    getDictData('order_type');
    if (this.advancedForm.order_time_range) {
      this.params.start_time = this.advancedForm.order_time_range[0].getTime() / 1000
      this.params.end_time = this.advancedForm.order_time_range[1].getTime() / 1000
    }
    this.getOrderList();
  },
  methods: {
    /**
      * @date 2020/09/01
      * @author kaiqiang
      * @description { 通过点击退补金额来判断他需要输入那个类型的值 }
    */
    handleRefundMoney(e) {
      this.event = e;
    },
    /**
      * @date 2020/09/01
      * @author kaiqiang
      * @description { 提交多退少补表单并验证 }
    */
    submitAudit(moreRefundForm) {
      let array = [];
      for (let i in this.multipleSelection) {
        array.push(this.multipleSelection[i].sn)
      }
      if (!this.event) {
        this.$message.warning('随机数和固定数只能选一个哦!!!');
        return
      } else if (this.event === String(1)) {
        const params = this.moreRefundForm;
        if (!params.max_refund || !params.min_refund) {
          this.$message.warning('随机数的最大值和最小值都不能为空!!!');
          return
        }
      } else {
        const params = this.moreRefundForm;
        if (!params.fix_refund) {
          this.$message.warning('固定数不能为空!!!');
          return
        }
      }
      this.$refs[moreRefundForm].validate((valide) => {
        if (valide) {
          let decide = this.moreRefundForm;
          if (decide.max_refund < decide.min_refund) {
            this.$message.error('最大值不能不能小于最小值!!!')
            return
          }
          delete decide.test
          API_ORDER.addRetreat(array, this.moreRefundForm).then((response) => {
            this.moreRefundForm = {
              ...this.moreRefundForm
            };
            this.event = undefined;
            this.auditDialog = false;
            this.$message.success('操作成功!!!');
            response.forEach(item => {
              this.$notify({
                title: '提示',
                message: item,
                type: 'warning',
                duration: 0
              });
            })
          })
        }
      })
    },
    /**
      * @date 2020/09/03
      * @author kaiqiang
      * @description { 取消表单并验证 }
    */
    handlerCancel() {
      this.auditDialog = false;
      this.event = undefined;
      this.$refs['moreRefundForm'].resetFields();
      this.$message.warning('操作已经取消!!!');
    },
    /**
      * @date 2020/08/22
      * @author 张凯强
      * @description {多退少补弹框}
    */
    auditIt() {
      for (let item in this.multipleSelection) {
        let self = this.multipleSelection[item];
        if (self.order_status_text === '已取消') {
          this.$message.error('多退少补订单状态不能是已取消的!!!');
          return
        } else if (self.service_status === 'APPLY') {
          this.$message.error('多退少补售后状态不能是已申请的!!!');
          return
        }
      }
      this.selectLength === 0 ? this.$message.warning('您还没有选择数据哦!!!') : this.auditDialog = true;
    },
    /**
     * @date 2020/06/17
     * @author kjh
     * @description { 页面初始化订单列表 }
     */
    getOrderList() {
      this.loading = true;
      API_LEADER.getOrderList(this.params)
        .then(response => {
          this.loading = false;
          this.tableData = response.data;
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          };
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
      * @date 2020/09/15
      * @author 张凯强
      * @description { 表格排序 }
    */
    tableSortChange(column) {
      let _this = this;
      this.params.page_no = 1;
      if (column.prop === "sorting_seq") {
        if (column.order === 'descending') {
          _this.params.order_fields = [];
          _this.sorting = 'SORTING_DESC';
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.params.order_fields.push(_this.sorting)
          _this.getOrderList();
        } else if (column.order === 'ascending') {
          _this.params.order_fields = [];
          _this.sorting = 'SORTING_ASC';
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.params.order_fields.push(_this.sorting)
          _this.getOrderList();
        } else if (column.order === null) {
          _this.sorting = undefined;
          _this.params.order_fields = [];
          _this.sorting = undefined;
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.getOrderList();
        }
      } else if (column.prop === "create_time") {
        if (column.order === 'descending') {
          _this.params.order_fields = [];
          _this.ctm = 'CTM_DESC';
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.params.order_fields.push(_this.ctm)
          _this.getOrderList();
        } else if (column.order === 'ascending') {
          _this.params.order_fields = [];
          _this.ctm = 'CTM_ASC';
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.params.order_fields.push(_this.ctm)
          _this.getOrderList();
        } else if (column.order === null) {
          _this.params.order_fields = [];
          _this.ctm = undefined;
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.sites === '' ? undefined : _this.params.order_fields.push(_this.sites);
          _this.getOrderList();
        }
      } else if (column.prop === "leader_name") {
        if (column.order === 'descending') {
          _this.params.order_fields = [];
          _this.sites = 'SITE_DESC';
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.params.order_fields.push(_this.sites)
          _this.getOrderList();
        } else if (column.order === 'ascending') {
          _this.params.order_fields = [];
          _this.sites = 'SITE_ASC';
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.params.order_fields.push(_this.sites)
          _this.getOrderList();
        } else if (column.order === null) {
          _this.params.order_fields = [];
          _this.sites = undefined;
          _this.sorting === '' ? undefined : _this.params.order_fields.push(_this.sorting);
          _this.ctm === '' ? undefined : _this.params.order_fields.push(_this.ctm);
          _this.getOrderList();
        }
      }
    },
    /**
      * @date 2020/08/20
      * @author kjh
      * @description {分页大小发生改变}
    */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.getOrderList();
    },
    /**
      * @date 2020/08/20
      * @author kjh
      * @description {分页页数发生改变}
    */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.getOrderList();
    },
    /**
      * @date 2020/08/20
      * @author kjh
      * @description {搜索事件触发}
    */
    searchEvent(data) {
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.order_time_range) {
        this.params.start_time = this.advancedForm.order_time_range[0].getTime() / 1000
        this.params.end_time = this.advancedForm.order_time_range[1].getTime() / 1000
      }

      this.params = {
        ...this.params,
        page_no: 1,
        page_size: 10,
        ...this.advancedForm,
        keyword: data
      };
      delete this.params.order_time_range;
      for (const _key in  this.params) {
        if (this.params[_key] === '') { // 当条件值为''时去除条件
          delete this.params[_key];
        }
      }
      this.getOrderList();
    },
    /**
      * @date 2020/08/19
      * @author kjh
      * @description {高级搜索}
    */
    advancedSearchEvent() {
      this.params = {
        page_no: 1,
        page_size: 10,
        ...this.advancedForm
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.order_time_range) {
        this.params.start_time = this.advancedForm.order_time_range[0].getTime() / 1000
        this.params.end_time = this.advancedForm.order_time_range[1].getTime() / 1000
      }
      delete this.params.keywords;
      delete this.params.order_time_range;
      for (const _key in  this.params) {
        if (this.params[_key] === '') { // 当条件值为''时去除条件
          delete this.params[_key];
        }
      }
      this.getOrderList();
    },
    /**
      * @date 2020/08/19
      * @author kjh
      * @description {获取会员信息}
    */
    getMemberList(query) {
      this.remote_loading = true;
      let params = {
        keyword: query,
        page_no: 1,
        page_size: 999
      };
      API_LEADER.getMemberList(params)
        .then(response => {
          this.remote_loading = false;
          this.options = response.data;
        })
        .catch(() => {
          this.remote_loading = false;
        });
    },
    /**
      * @date 2020/07/24
      * @author kjh
      * @description {多选框赋值}
    */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.selectLength = val.length
    },
    /**
      * @date 2020/08/18
      * @author kjh
      * @description {批量发货弹框触发，以及获取物流公司的下拉列表 这里因为不能同时获取到}
    */
    deliveryOrder() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择商品！');
        return;
      }
      // 部分表单数据清空
      this.goodSendForm.logi_id = '';
      this.goodSendForm.ship_no = '';
      for (let item of this.multipleSelection) {
        if ((item.order_status !== 'PAID_OFF' && item.order_status !== 'FORMED' ) || item.service_status === 'APPLY' ) {
          this.$message.warning('选中的订单中存在售后中或非待发货的订单，不能发货！');
          return;
        }
      }
      this.s_logi_option = [];
      API_Receipt.queryExpressList().then(response => {
        if (!response.length) {
          this.$message.error('没有物流公司，请先去设置')
        }
        response.forEach(item => {
          let params = {
            name: item.logistics_company_do.name,
            id: item.logistics_company_do.id
          }
          this.s_logi_option.push(params);
        })
      }).catch()
      this.goodSendForm.shipping_type = "GLOBAL";
      this.goodDialogVisible = true;
    },
    /**
      * @date 2020/10/16
      * @author wolfMan
      * @description {修改收货地址}
    */
    uploadReceipt(_row) {
      console.log(_row)
      this.$nextTick(() => {
        if (this.$refs['receiptForm'] !== undefined) {
          this.$refs['receiptForm'].clearValidate();
          this.areas = [];
        }
      });
      this.receiptDialog = true;
      if (_row.leader_id === -1) {
        _row.leader_id = null;
      }
      if (_row.shipping_type === 'SELF') {
        this.siteNames = [{
          leader_id: _row.leader_id,
          leader_name: _row.leader_name,
          site_name: _row.site_name,
          address: _row.address
        }];
      } else {
        this.siteNames = [];
      }
      this.$nextTick(() => {
        this.receiptForm = {
          order_sn: _row.sn,
          shipping_type: _row.shipping_type,
          leader_id: _row.leader_id,
          ship_name: _row.ship_name,
          ship_mobile: _row.ship_mobile,
          // site_name: _site_name,
          ship_addr: _row.ship_addr,
          province_id: _row.ship_province_id,
          city_id: _row.ship_city_id,
          county_id: _row.ship_county_id,
          town_id: _row.ship_town_id,
          index_region: _row.ship_town_id || _row.ship_county_id
        }
        if ( _row.ship_province_id === -1) {
          this.areas = []
        } else {
          this.areas = [
            _row.ship_province_id,
            _row.ship_city_id,
            _row.ship_county_id || -1,
            _row.ship_town_id || -1
          ]
        }
      });
    },
    /**
      * @date 2020/10/15
      * @author kaiqiang
      * @description {动态获取自提点}
    */
    remoteMethod(query) {
      if (query !== '') {
        this.getLeaderList(query);
      } else {
        this.siteNames = [];
      }
    },
    /**
      * @date 2020/10/15
      * @author kaiqiang
      * @description {获取自提点列表}
    */
    getLeaderList(query) {
      let params = {
        'site_name': query
      }
      API_LEADER.querySiteName(params).then(response => {
        this.siteNames = response;
      }).catch((error) => {
        console.log(error)
      })
    },
    /**
      * @date 2020/10/15
      * @author kaiqiang
      * @description {地址修改提交}
    */
    receiptSubmit(receiptForm) {
      this.$refs['receiptForm'].validate((valide) => {
        if (valide) {
          // let params = {
          //   ''
          // }
          API_LEADER.updOrderAddress(this.receiptForm).then(response => {
            this.$message.success(response.message);
            this.receiptDialog = false;
            this.getOrderList();
          }).catch((error) => {
            console.log(error)
            this.receiptDialog = false;
          });
        }
      })
    },
    /**
      * @date 2020/08/18
      * @author kjh
      * @description {确认批量发货}
    */
    sendGoods () {
      let _selectSns = this.getSelectSn(); //批量获取订单号
      let _sns = _selectSns.toString();  //将订单号转化成字符串
      let _name = '';  //根据logi_id获取物流公司的名字logi_name
      this.s_logi_option.forEach(item => {
        if (this.goodSendForm.logi_id === item.id){
          _name = item.name;
        }
      })
      let _params = {
        ...this.goodSendForm,
        logi_name: _name
      };
      if (_selectSns.length > 0) {
        API_LEADER.apiDeliveryOrder(_sns, _params).then((res) => {
          this.$message.success('发货成功');
          this.getOrderList();
        });
      }
      this.goodDialogVisible = false;
    },
    /**
      * @date 2020/08/19
      * @author kjh
      * @description {导出订单}
    */
    exportOrder() {
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.order_time_range) {
        this.params.start_time = this.advancedForm.order_time_range[0].getTime() / 1000
        this.params.end_time = this.advancedForm.order_time_range[1].getTime() / 1000
      }
      let _params = {
        ...this.params,
        ...this.advancedForm
      };
      delete _params.order_time_range;
      for (const _key in  _params) {
        if (_params[_key] === '') { // 当条件值为''时去除条件
          delete _params[_key];
        }
      }
      API_ORDER.exportGoodsOrder(_params).then(response => {
        // 处理返回的文件流
        let blob = new Blob([response], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        });
        let date = new Date().getFullYear() + '' + (new Date().getMonth() + 1) + '' + new Date().getDate();
        const fileName = date + name + '商品sku导出.xlsx';
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      })
    },
    /**
      * @date 2020/08/20
      * @author kjh
      * @description {批量获取订单号}
    */
    getSelectSn() {
      let _selectSns = [];
      this.multipleSelection.forEach(item => {
        _selectSns.push(item.sn);
      })
      return _selectSns;
    },
    /**
      * @date 2020/08/19
      * @author kjh
      * @description {打印小票的弹窗触发}
    */
    openDialog() {
      if (!this.multipleSelection.length) {
        this.$message.warning(`请选择订单！`);
        return;
      }
      this.btn_loading = true;
      this.printText = '加载数据中';
      this.DialogVisible = true;
      let _selectSns = this.getSelectSn();
      let _sns = _selectSns.toString();
      API_ORDER.getByOrderSnList(_sns).then(response => {
        this.btn_loading = false;
        this.printText = '打印小票';
        this.printOrder = response;
      }).catch(() => { this.btn_loading = false; })
    },
    /**
      * @date 2020/08/19
      * @author kjh
      * @description {使预览的内容得到显示}
    */
    previewOrder() {
      document.getElementById('mycontent').style.display="block";
    },
    /**
      * @date 2020/07/22
      * @author kjh
      * @description {打印配送单}
    */
    printPdf () {
      this.btn_loading = true;
      setTimeout(() => {
        let LODOP = getLodop();
        LODOP.PRINT_INIT('面单打印');
        LODOP.SET_PRINT_STYLE('FontSize', 15);
        LODOP.SET_PRINT_PAGESIZE(3, 1200, 80, '');
        LODOP.SET_PRINT_STYLE('Bold', 1);
        LODOP.ADD_PRINT_HTM(0, 0, '100', '70%', document.getElementById('advancePrint').innerHTML);
        // LODOP.PREVIEW();
        LODOP.PRINT();
        this.DialogVisible = false;
        this.btn_loading = false;
      }, 1000);
    },
    // 查看团购订单详情
    handleGroupDetail(row) {
      this.$router.push({ path: `/order/detail/${row.sn}` });
    },
    /** 条件重置 */
    resetForm (formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
        if (formName === 'receiptForm') {
          this.areas = [];
          this.siteNames = [];
        }
      }
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>

  /deep/ .app-address {
    width: 100% !important;
    height: 32px;
    .app-address-title {
      padding: 0 20px 0 15px;
      height: 32px;
      line-height: 32px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      color: #606266;
    }
  }
  div.toolbar-btns {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-items: center;
    div {
      span {
        display: inline-block;
        font-size: 14px;
        color: #606266;
      }
    }
    .conditions {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: flex-start;
      align-items: center;
      min-width: 24.5%;
      .choose-machine {
        width: 60%;
      }
    }
  }
  //顶部工具栏样式
  .inner-toolbar{
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
  }
  //设置对话框中的两个按钮居中
  .footer {
    display: flex;
    justify-content: center;
  }
  .select-get{
    width: 100%;
  }
  //设置对话框内的输入框宽度
  .select-type {
    width: 300px;
  }
  .myselect-type {
    width: 349px;
  }
  //设置远程搜索(关联用户)左右对齐
  .mobile {
    float: right;
  }
  .myred {
    margin-bottom: 20px;
    color: red;
  }
  .bottomred {
    color: red;
  }
  .goods-image {
    width: 50px;
    height: 50px;
    }
  .goods-name {
    margin-left: 20px;
    top:50%;
    left: 50%;
    text-align: left;
  }
  .mytable {
    display: flex;
    color: #FD7F26;
    text-align: center;
    margin-top: 20px;
  }
  .top-dialog {
    margin-bottom: 20px;
    font-size: 18px;
  }
  .dialog-radio {
    margin-bottom: 20px;
    .upadate-radio {
      margin-top: 6px;
    }
  }
  .distance {
    margin: 10px;
  }
  .math-number {
    line-height: 30px;
  }
  /deep/ .el-input__inner {
    padding: 0 10px;
  }
  .font-color {
    color: red;
  }
  .sn-color {
    color: #00a2d4;
    cursor: pointer;
  }
  /deep/ .el-dialog__body {
    padding: 10px 20px;
  }
  .sn-color {
    color: "#00a2d4";
    cursor: pointer;
  }
  .el-select {
    width: 100%;
  }
</style>
<style type="text/scss" lang="scss">
  .toolbar-input .el-form-item__label {
    font-weight: normal;
  }
  .el-date-editor--datetimerange.el-input, .el-date-editor--datetimerange.el-input__inner {
    width: 349px;
  }
  .column-color {
    color: #fff;
    &:nth-child(1) {
      background-color: #3d81e5 !important;
    }
    &:nth-child(2){
      background-color: #ffc09f !important;
    }
  }
  /* element样式重置 start */
  /* 去掉input尾部上下小箭头 start */
  input::-webkit-outer-spin-button,input::-webkit-inner-spin-button{
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    -o-appearance: none !important;
    -ms-appearance: none !important;
    appearance: none !important;
    margin: 0;
  }
  input[type="number"]{
    -webkit-appearance:textfield;
    -moz-appearance:textfield;
    -o-appearance:textfield;
    -ms-appearance:textfield;
    appearance:textfield;
  }
  /* 去掉input尾部上下小箭头 end */
  .previewDiv{
    position: relative;
  }
</style>
